package maven.jyhs.com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Controller
public class FileUploadController {

    // 上传文件的保存路径（这里使用项目根目录下的uploads文件夹）  
    private static String UPLOADED_FOLDER = System.getProperty("user.dir") + "/uploads/";

    @PostMapping("/upload")
    public String multiFileUpload(@RequestParam("files") List<MultipartFile> files, Model model) {
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    // 获取文件名  
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                    Files.write(path, bytes);

                    // 在这里你可以添加更多逻辑，比如将文件信息保存到数据库  

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        model.addAttribute("message", "文件上传成功!");
        return "result"; // 返回结果页面  
    }
}